package tcpUSServer;

import util.*;
import java.net.*;
import java.sql.SQLException;
import java.util.*;
import java.io.*;

import db.DB;

public class UpdateSupportServer extends Thread{
	
	// The socket to the client
	SocketManager socketToClient;
	
	private DB dataBase = new DB();
	
	// Create a SocketManager to manage the socket to the client
	public UpdateSupportServer(Socket s) throws IOException{			
		socketToClient = new SocketManager(s);
		System.out.println("Connection from " + s.getInetAddress().getHostAddress());
	}
	
	// Implement the basic file info protocol
    public void run(){
    	List<String> commandList = Arrays.asList("USER", "PASS", "GET_FILE", "QUIT");
    	int state = 0;
    	String uname = "";
    	String message, command;
    	String path="/alumno/";
        try{
        	for(;state!=3;){
        		message = socketToClient.read();
        		StringTokenizer st = new StringTokenizer(message);
        		command = st.nextToken();
        		switch(state){
        			case 0:
        				if(command.equalsIgnoreCase("USER")){
        					uname = st.nextToken();
                            if(validate(uname))
                            {
                            	socketToClient.write("OK Welcome " + uname + "\r\n"); 
                            	System.out.println("estoy en state 1");
                                state = 1;
                            }
                            else
                            {
                            	System.out.println("incorrect user");
                            }
        				} else if (command.equalsIgnoreCase("QUIT")){
        					state = 3;
        				}else if(commandList.contains(command)){
        					socketToClient.write("500 Command not permitted in this state\r\n");
        				} else{
        					socketToClient.write("500 Unknown command\r\n");
        				}
        				break;
        			case 1:
        				if(command.equalsIgnoreCase("PASS")){
        					 String password = st.nextToken();
                             if(validate(uname, password))
                             {
                                     socketToClient.write("202 OK Welcome to the system\r\n");
                                     System.out.println("estoy en state 2");
                                     state = 2;
                             }
                             else if(password==null)
                             {
                                     socketToClient.write("403 ERR Missing password parameter\r\n");
                             }
                             else
                             {
                                     socketToClient.write("402 ERR Authentication error\r\n");
                                     state = 0;
                             }
        				} else if (command.equalsIgnoreCase("QUIT")){
        					state = 3;
        				} 
        				break;
        			case 2:
        				System.out.println("estoy en state 2");
        				if(command.equalsIgnoreCase("GET_FILE"))
        				{
						// create socket
						//    while (true) {
        					  ServerSocket servsock = new ServerSocket(13267);
						      System.out.println("Waiting...");
		
						      Socket sock = servsock.accept();
						      //System.out.println("Accepted connection : " + sock);
		
						      // sendfile
						      File myFile = new File ("data/configuration.doc");
						      byte [] mybytearray  = new byte [(int)myFile.length()];
						      FileInputStream fis = new FileInputStream(myFile);
						      BufferedInputStream bis = new BufferedInputStream(fis);
						      bis.read(mybytearray,0,mybytearray.length);
						      OutputStream os = socketToClient.getSocket().getOutputStream();
						      System.out.println("Sending...");
						      os.write(mybytearray,0,mybytearray.length);
						      socketToClient.write("240\r\n");
						      os.flush();
						      sock.close();	
        				}
        				else if(commandList.contains(command)){
        					socketToClient.write("500 Command not permitted in this state\r\n");
        				} else{
        					socketToClient.write("500 Unknown command\r\n");
        				}
        				break;
        		}
            }	            
        	socketToClient.write("203 Bye\r\n");
            // Release resources
            socketToClient.closeStreams();
            socketToClient.closeSocket();
        }catch(Exception e){
            System.err.println("main: " + e);
            e.printStackTrace();
        }
}
    
    public boolean validate(String user, String pass){
    	// Fake function, normally a database should be accessed, ...
    	return true;
    }
    
    public String[] getFileList(String path){
    	File f = new File(path);
    	return f.list();
    }
    
    public boolean validate(String user)
	{
		boolean validate = false;
		try
		{
			dataBase.connect();
			validate = dataBase.correctUserLogin(user);
			dataBase.disconnect();
		}
		catch (ClassNotFoundException e) {e.printStackTrace();}
		catch (SQLException e) {e.printStackTrace();}
		
		return validate;
	}

}
